import 'package:flutter/material.dart';
import 'package:novel_reader/model/book.dart';
import 'package:novel_reader/model/chapter.dart';
import 'package:novel_reader/utils/hive_storage.dart';
import 'package:novel_reader/utils/reader_operation.dart';
import 'package:novel_reader/utils/utils.dart';
import 'package:novel_reader/widgets/fixed_adaptive_width_dropdown.dart';
import 'package:shared_preferences/shared_preferences.dart';

class BookChapterSelector extends StatefulWidget {
  final List<Book> bookData;
  final Function(Book, List<Chapter>, Chapter, bool) onChapterSelected;

  const BookChapterSelector({
    super.key,
    required this.bookData,
    required this.onChapterSelected,
  });

  @override
  BookChapterSelectorState createState() => BookChapterSelectorState();
}

class BookChapterSelectorState extends State<BookChapterSelector> {
  final String cacheBookKey = 'lastSelectedBook';
  Book? selectedBook;
  Chapter? selectedChapter;
  List<Chapter> chapters = [];

  @override
  void didUpdateWidget(covariant BookChapterSelector oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (selectedBook == null && oldWidget.bookData.isEmpty) {
      _initializeSelection();
    }
  }

  void _initializeSelection() async {
    final prefs = await SharedPreferences.getInstance();
    var defaultSelectedBook = prefs.getString(cacheBookKey);
    setState(() {
      if (defaultSelectedBook != null) {
        selectedBook = HiveStorage.getBookByCode(defaultSelectedBook);
      }
      if (selectedBook == null && widget.bookData.isNotEmpty) {
        selectedBook = widget.bookData.first;
      }
      _loadChapters();
    });
  }

  void _loadChapters() {
    if (selectedBook != null) {
      List<Chapter> chapters2 = HiveStorage.getChaptersByBookCode(
        selectedBook!.code,
      );
      int index = 1;
      for (Chapter chapter in chapters2) {
        chapter.index = index++;
      }
      setState(() {
        chapters = chapters2;
        var reading = selectedBook!.reading ?? 0;
        if (reading < 0) {
          reading = 0;
        }
        if (reading < chapters.length) {
          selectedChapter = chapters[reading];
        } else if (chapters.isNotEmpty) {
          selectedChapter = chapters.first;
        }
        if (selectedChapter != null) {
          widget.onChapterSelected(
            selectedBook!,
            chapters,
            selectedChapter!,
            false,
          );
        }
      });
    }
  }

  Future<void> _cacheSelectedBook(Book book) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(cacheBookKey, book.code);
  }

  void _onBookChanged(Book? newValue) {
    if (newValue == null) return;
    setState(() {
      selectedBook = newValue;
      _loadChapters();
      widget.onChapterSelected(newValue, chapters, selectedChapter!, false);
    });
    _cacheSelectedBook(newValue);
  }

  void _onChapterChanged(Chapter? newValue) {
    if (newValue == null) return;
    setState(() => selectedChapter = newValue);
    widget.onChapterSelected(selectedBook!, chapters, newValue, false);
  }

  void _switchChapter(int index) {
    if (chapters.isEmpty) return;
    if (index > -1) {
      if (index < chapters.length) {
        _onChapterChanged(chapters[index]);
      } else {
        Utils.showToast(context, '到边了');
      }
    } else {
      Utils.showToast(context, '到边了');
    }
  }

  void previousChapter() {
    final index = selectedBook!.reading;
    if (index != null) {
      _switchChapter(index - 1);
    }
  }

  void nextChapter() {
    final index = selectedBook!.reading;
    if (index != null) {
      _switchChapter(index + 1);
    }
  }

  void updateChapters(ReaderOperation? readerOperation) {
    readerOperation?.updateChapters(selectedBook, () => _loadChapters());
  }

  void updateChapter(ReaderOperation? readerOperation) {
    widget.onChapterSelected(selectedBook!, chapters, selectedChapter!, true);
  }

  void removeBook(ReaderOperation? readerOperation) {
    if (selectedBook == null) {
      Utils.showToast(context, '当前没有选择的书籍');
      return;
    }
    Utils.showConfirmDialog(context, '是否确定删除书籍“${selectedBook?.name}”？', () {
      readerOperation?.removeBook(selectedBook!, widget.bookData, () {
        if (widget.bookData.isNotEmpty) {
          _onBookChanged(widget.bookData[0]);
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        FixedAdaptiveWidthDropdown<Book>(
          items: widget.bookData,
          value: selectedBook,
          onChanged: _onBookChanged,
        ),
        SizedBox(width: 6),
        FixedAdaptiveWidthDropdown<Chapter>(
          items: chapters,
          value: selectedChapter,
          onChanged: _onChapterChanged,
        ),
      ],
    );
  }
}
